import React from 'react'
// { useEffect, useState }
import { useState } from 'react'
import axios from 'axios'
import { Badge, Card, Tooltip, Input } from 'antd'
import { message } from 'antd'
import { Tag } from 'antd'
// import HyperDown from 'hyperdown'
import {
  LinkOutlined,
  SendOutlined,
  FolderOpenOutlined,
  OrderedListOutlined,
  FolderOutlined,
} from '@ant-design/icons'
import "./OneCard.css"
import { SearchList } from './SearchList'
function OneCard ({ linkData: { component, imgSrc, imgSrcBg, imgSrcBgHeight, url, url2, title, tip, focus, folder, sendMessage, text, icon = 'default', tag, execDoIt, blank = "_blank" },
  badgeBool, index, folderOnClick, setSearchText, border }) {
  // let parser = new HyperDown()

  const { Search } = Input
  const [mySearchText, setMySearchText] = useState('')

  let imageTopBg
  if (imgSrcBg) {
    const imgSrcBgHeight1 = imgSrcBgHeight ? imgSrcBgHeight : '98px'
    const cn = defineCss(`${imgSrcBg.replace('.', '')}ClassName`, `
        background-image: url("./uploads/images/${imgSrcBg}");
        height: ${imgSrcBgHeight1};
        border-radius: 3px 3px 0 0;
    `)
    imageTopBg = (
      <div className={cn}></div>
    )
  }

  let imageTop
  if (imgSrc) {
    imageTop = (
      <img
        src={"uploads/images/" + imgSrc}
        style={{
          width: "100%",
          borderRadius: "3px 3px 0 0",
        }}
        alt="pic"
      ></img>
    )
  }

  let folderLine
  if (folder) {
    folderLine = <div style={{ backgroundColor: "#dbb635", height: "10px" }}></div>
  }

  let colorLine
  if (!imgSrc && !imgSrcBg && !focus && !folder) {
    const color = "#5ba4cf"
    colorLine = <div style={{ backgroundColor: color, height: "10px" }}></div>
  }

  let tipComponent
  if (tip) {
    tipComponent = (
      <Tooltip placement="bottom" color="#5c6367" title={tip}>
        <OrderedListOutlined style={{ marginRight: "5px" }} />
      </Tooltip>
    )
  }

  let sendMessageComponent
  if (sendMessage) {
    sendMessageComponent = (
      <SendOutlined onClick={event => {
        console.log(title + " > " + sendMessage)
        event.preventDefault()
      }} />
    )
  }

  let tagComponent
  if (tag) {
    const tagArr = tag.split(",")
    tagComponent = tagArr.map((item, index) => {
      return (
        <Tag color="#108ee9" key={index}>{item}</Tag>
      )
    })
  }

  let url2Component
  if (url2) {
    url2Component = (
      <a style={{
        ...aStyle,
        marginRight: "5px",
        float: 'left',
      }} href={url2} target={blank} title="备份跳转" rel="noopener noreferrer" >
        <LinkOutlined />
      </a >
    )
  }

  let bottomLine
  if (tip || sendMessage || tag) {
    bottomLine = (
      <div style={tipStyle}>
        {tipComponent} {sendMessageComponent} {tagComponent} {url2Component}
      </div>
    )
  }

  let focusComponent
  if (focus) {
    focusComponent = (
      <div style={focusStyle}>
        {focus}
      </div>
    )
  }

  let folderComponent
  if (folder) {
    folderComponent = badgeBool ? <FolderOpenOutlined style={{ marginRight: '5px' }} /> : <FolderOutlined style={{ marginRight: '5px' }} />
  }

  let textComponent
  if (text) {
    textComponent = (
      <div style={{
        padding: "5px 12px 0 12px",
        color: "#666"
      }}>
        {text}
      </div>
    )
  }

  let iconComponent
  if (!folder && icon !== '') {
    iconComponent = (
      <span className={"rootIcons"} style={{
        ...iconStyle,
        backgroundPosition: getIconPosition(icon),
      }} ></span>
    )
  }

  // let [md1, setMd1] = useState(md)
  // useEffect(() => {
  //   if (md) {
  //     fetch(md).then(res => res.text()).then(text => setMd1(text))
  //   }
  // }, [md])

  // let mdComponent
  // if (md) {
  //   mdComponent = (
  //     <div dangerouslySetInnerHTML={{ __html: parser.makeHtml(md1) }} style={{ margin: "0 12px" }}>
  //     </div>
  //   )
  // }

  function getIconPosition (iconName) {
    const [x, y] = iconListJson[iconName]
    return "left -" + x * 30 + "px top -" + y * 30 + "px"
  }

  function oneCardOnClick (event) {
    if (folder) {
      folderOnClick(index)
    } else {
      if (!window.linkOpen) {
        event.preventDefault()
      } else {
        if (execDoIt) { // 执行api
          event.preventDefault()
          let isNeedShow = true
          setTimeout(function () {
            isNeedShow && message.loading({ content: '正在努力尝试打开...', key: 'execDoIt' })
          }, 100)
          axios.post('http://localhost:31187/api/tools/execDoIt', { command: `start c:\\windows\\explorer.exe ${url}` }).then(res => {
            console.info('execDoIt 20220407', res)
            isNeedShow = false
            message.success({ content: '运行成功', key: 'execDoIt' })
          }).catch(err => {
            message.error({ content: '请运行navigator-backend服务后再进行点击', key: 'execDoIt', duration: 4 })
          })
        }
      }
    }
  }

  function AUrl (props) {
    if (url || folder) {
      return (
        <a style={aStyle} href={url} onClick={oneCardOnClick} target={blank} rel="noopener noreferrer">
          {props.children}
        </a>
      )
    }
    return (
      <>
        {props.children}
      </>
    )
  }

  let titleComponent
  if (title) {
    titleComponent = (
      <div style={{ padding: '12px', paddingBottom: 0, lineHeight: '22px' }}>
        {folderComponent}
        {iconComponent}
        {title}</div>
    )
  }

  function baiduOnSearch (text, event) {
    console.info('baiduOnSearch text ', text)
    if (text) {
      window.open("https://www.baidu.com/s?wd=" + text)
    }
  }
  if (component === 'baidu') {
    return (
      <Card size="small" className="navigator-ant-card" style={innerCardStyle}>
        <Search placeholder="百度搜索" allowClear onSearch={baiduOnSearch} enterButton />
      </Card>
    )
  }

  function translateOnSearch (text, event) {
    if (text) {
      window.open("https://fanyi.baidu.com/#en/zh/" + text)
    }
  }
  if (component === 'translate') {
    return (
      <Card size="small" className="navigator-ant-card" style={innerCardStyle}>
        <Search placeholder="单词翻译" allowClear onSearch={translateOnSearch} enterButton />
      </Card>
    )
  }


  let searchValue = ''
  function pageOnSearch (text, event) {
    console.info('pageOnSearch event', event, text)
    if (text === '') {
      return false
    }
    // console.info('pageOnSearch text ', searchValue, text, text.target.value)
    // pageOnSearchCore(text)
    const urlObj = funcs.getUrl()
    if (urlObj.status) {
      window.open(urlObj.url)
      return false
    }
    baiduOnSearch(text)
  }
  function pageOnChange (e) {
    funcs.setIndex(0)
    pageOnSearchCore(e.target.value)
  }
  function pageOnSearchCore (text) {
    setMySearchText(text)
  }
  let funcs = {
    getUrl: () => { },
    setIndex: () => { },
    addIndex: () => { },
    subIndex: () => { },
  }
  function pageOnkeydown (e) {
    // keyCode 38 up 40 down
    if (e.keyCode === 38) {
      funcs.subIndex()
    }
    if (e.keyCode === 40) {
      funcs.addIndex()
    }
  }

  if (component === 'pageSearch') {

    const A111 = (
      <Card size="small" className="navigator-ant-card" style={innerCardStyle}>
        <Search defaultValue={searchValue}
          onKeyUp={pageOnkeydown}
          placeholder="页面搜索"
          allowClear
          onChange={pageOnChange}
          onSearch={pageOnSearch}
          enterButton />
      </Card>
    )

    return (
      <div>
        {A111}
        <SearchList funcs={funcs} text={mySearchText}></SearchList>
      </div>
    )
  }

  const cardClassName = border ? "selectSearchItemByNavi navigator-ant-card" : "navigator-ant-card"
  return (
    <div>
      <Badge dot={badgeBool}>
        <Card size="small"
          className={cardClassName} style={innerCardStyle}>
          <AUrl>
            {focusComponent}
            {imageTop}
            {imageTopBg}
            {colorLine}
            {folderLine}
            {titleComponent}
            {/* {mdComponent} */}
          </AUrl>
          {textComponent}
          {bottomLine}
          <div style={{ height: "12px" }}></div>
        </Card>
      </Badge>
    </div>
  )
}

export default OneCard

const defineCss = (className, styleBlock) => {
  const exist = document.getElementById(className)
  // console.info('exist', exist)
  if (!exist) {
    const styleEl = document.createElement('style')
    styleEl.id = className
    styleEl.textContent = `
      .${className} {
        ${styleBlock}
      }
    `
    document.head.appendChild(styleEl)
  }
  return className
}

const aStyle = {
  display: "block",
  color: "#172b4d",
}

const innerCardStyle = {
  display: "block",
  padding: 0,
}

const tipStyle = {
  padding: "8px 12px 0 12px",
  // marginTop: "0px",
}

const focusStyle = {
  height: "70px",
  lineHeight: "70px",
  textAlign: "center",
  width: "100%",
  backgroundColor: "#4b4b4b",
  color: "white",
  fontSize: "40px",
  borderRadius: "3px 3px 0 0",
}

const iconStyle = {
  height: "22px",
  width: "22px",
  // backgroundColor: "black",
  // backgroundImage: "url('./assets/images/icons.jpg?ra=" + Math.random() + "')",
  float: "left",
  marginRight: "5px",
  borderRadius: "50%",
}

const iconListJson = {
  "orange": [0, 0],
  "cnblogs": [1, 0],
  "gitee": [2, 0],
  "github": [3, 0],
  "excel": [4, 0],
  "zentao": [5, 0],
  "juejin": [6, 0],
  "aa": [7, 0],
  "yuque": [8, 0],
  "baidufanyi": [9, 0],
  "react": [0, 1],
  "dicts": [1, 1],
  "huaban": [2, 1],
  "trello": [3, 1],
  "iiter": [4, 1],
  "hskyun": [5, 1],
  "iview": [6, 1],
  "process": [7, 1],
  "gitlab": [8, 1],
  "json": [9, 1],
  "sourcetree": [0, 2],
  "umi": [1, 2],
  "es6": [2, 2],
  "segmentfault": [3, 2],
  "overflow": [4, 2],
  "xunjiepdf": [5, 2],
  "vue": [6, 2],
  "jsrun": [7, 2],
  "doclever": [8, 2],
  "baidu": [9, 2],
  "processon": [0, 3],
  "drawio": [1, 3],
  "typescript": [2, 3],
  "ibaotu": [3, 3],
  "iconfont": [4, 3],
  "lettera": [5, 3],
  "cloud": [6, 3],
  "dog": [7, 3],
  "bilibili": [8, 3],
  "codelf": [9, 3],
  "etymon": [0, 4],
  "etymonline": [1, 4],
  "merriam": [2, 4],
  "oxford": [3, 4],
  "cambridge": [4, 4],
  "forvo": [5, 4],
  "ozdic": [6, 4],
  "freecodecamp": [7, 4],
  "youtube": [8, 4],
  "default": [9, 4],
  "vlogcircle": [0, 5],
  "bigbigwork": [1, 5],
  "uisdc": [2, 5],
  "shejidaren": [3, 5],
  "46design": [4, 5],
  "littlefish": [5, 5],
  "catdog": [6, 5],
  "pocket": [7, 5],
  "operationschool": [8, 5],
  "operationcat": [9, 5],
  "spbang": [0, 6],
  "sunshinemovie": [1, 6],
  "kancloud": [2, 6],
  "c4d": [3, 6],
  "book": [4, 6],
  "color": [5, 6],
  "producthunt": [6, 6],
  "music163": [7, 6],
  "ECharts": [8, 6],
  "enpuz": [9, 6],
  "folder": [0, 7],
  "tencent": [1, 7],
  "danghui": [2, 7],
  "english": [3, 7],
  "java": [4, 7],
  "js": [5, 7],
  "doyoudo": [6, 7],
  "selfPlatform": [7, 7],
  "vant": [8, 7],
  "coderutil": [9, 7],
  "ruanyifeng": [0, 8],
  "google": [1, 8],
}